package 线程;

import org.omg.CORBA.REBIND;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:谢君臣
 * @Date:2021/9/21-15:32
 * @version:1.0
 * @function:
 */
public class 顺序打印 {
    static ReentrantLock lock = new ReentrantLock();
    static Condition c1 = lock.newCondition();
    static Condition c2 = lock.newCondition();
    static Condition c3 = lock.newCondition();
    private static int num = 1;
    public static void main(String[] args) {
        new Thread(()->{
            lock.lock();
            try {
                while (num<100){
                    if (num%3!=1){
                        c1.await();
                    }else{
                        System.out.println(Thread.currentThread().getName()+":"+num++);
                    }
                    c2.signal();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"t1").start();
        new Thread(()->{
            lock.lock();
            try {
                while (num<100){
                    if (num%3!=2){
                        c2.await();
                    }else{
                        System.out.println(Thread.currentThread().getName()+":"+num++);
                    }
                    c3.signal();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"t2").start();
        new Thread(()->{
            lock.lock();
            try {
                while (num<100){
                    if (num%3!=0){
                        c3.await();
                    }else{
                        System.out.println(Thread.currentThread().getName()+":"+num++);
                    }
                    c1.signal();
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        },"t3").start();
    }
}
